<template>
  <a 
    v-if="txHash"
    :href="`https://tronscan.org/#/transaction/${txHash}`"
    target="_blank"
    rel="noopener noreferrer"
    class="common-link"
    @click.stop
  >
    <slot>
      {{ displayText }}
    </slot>
  </a>
  <span v-else class="no-hash">--</span>
</template>

<script>
import { computed } from 'vue'

export default {
  name: 'CommonLink',
  props: {
    // 交易哈希值（必需）
    txHash: {
      type: String,
      default: ''
    },
    // 最大显示长度（默认12字符）
    maxLength: {
      type: Number,
      default: 12
    }
  },
  setup(props) {
    /**
     * 截断文本中间部分
     * @param {string} text - 要处理的文本
     * @param {number} left - 左侧保留字符数
     * @param {number} right - 右侧保留字符数
     * @returns {string} 处理后的文本
     */
    const cutMiddle = (text = '', left = 6, right = 6) => {
      if (typeof text !== 'string') return '';
      text = text.trim();
      if (text.length <= left + right) return text;
      return `${text.substring(0, left)}...${text.substring(text.length - right)}`;
    };

    // 计算显示文本
    const displayText = computed(() => {
      if (!props.txHash) return '';
      
      // 计算左右两侧保留的字符数（各占一半）
      const left = Math.floor(props.maxLength / 2);
      const right = Math.floor(props.maxLength / 2);
      
      return cutMiddle(props.txHash, left, right);
    });

    return {
      displayText
    }
  }
}
</script>

<style scoped>
.common-link {
  color: #1890ff;
  text-decoration: none;
  transition: all 0.3s;
  cursor: pointer;
  /* font-family: monospace; */
}
.common-link:hover {
  color: #40a9ff;
  text-decoration: none;
}
.no-hash {
  color: #999;
  font-style: italic;
}
</style>